<template>
  <p>出生年份{{ birthYear }}</p>
  <p>周岁 {{ age }}</p>
  <p>虚岁 {{ xusui }}</p>
</template>

<script>
import {
  toRefs,
  reactive,
  computed,
  onMounted,
  onUnmounted,
} from "vue";

function useAge() {
  const state = reactive({
    birthYear: 2004,
    age: 18,
  });

  /* 生命周期 */
  let timer = null;
  onMounted(() => {
    timer = setInterval(() => {
      state.age += 1;
    }, 1000);
  });

  onUnmounted(() => {
    clearInterval(timer);
    console.log("定时器已被移除");
  });

  /* 计算属性 */
  // 由年龄计算虚岁
  const xusui = computed(() => {
    return state.age + 1;
  });

  return {
    ...toRefs(state),
    xusui,
  };
}

export default {
  name: "WhyRef",
  setup() {
    /* 自定义hook */
    const { birthYear, age, xusui } = useAge();

    return {
      birthYear,
      age,
      xusui,
    };
  },
};
</script>
